package net.yambal.RTM.Items
{
	import flash.events.EventDispatcher;
	
	import net.yambal.RTM.Event.TimelineEvent;
	import net.yambal.RTM.Event.TransactionEvent;
	import net.yambal.RTM.RestWrapper.RestService;
	import net.yambal.RTM.Event.RestErrorEvent;
	import net.yambal.RTM.Event.RestEvent;
	import net.yambal.RTM.Utilty.RTMTimelineGetter;
	
	[Event(name="undo", type="net.yambal.RTM.Event.TransactionEvent")]
	[Event(name="cant_undo", type="net.yambal.RTM.Event.TransactionEvent")]
	public class RTMTransaction extends EventDispatcher
	{
		public var id:uint;
		public var undoable:Boolean;
		public var process:String;
		
		/**
		 * undo
		 **/
		public function undo(api_key:String, shared_secret:String, token:String):void{
			trace("undo");
			if(this.undoable){
				var tlg:RTMTimelineGetter = new RTMTimelineGetter();
				tlg.getTimeline(api_key, shared_secret, token, this.onGetTLForUndo);
				
			}else{
				// このトランザクションは取り消しできない
				trace("can't undo..." + this.undoable);
				this.dispatchEvent(new TransactionEvent(TransactionEvent.UNDO));
			}
		}
		
		private function onGetTLForUndo(e:TimelineEvent, ro:Object):void{
			trace("undo.onGetTLForUndo");
			var s:RestService = new RestService(RestService.METHOD_TRANSACTIONS_UNDO, e.shared_secret);
			s.addParameta("api_key", e.api_key);
			s.addParameta("auth_token", e.token);
			s.addParameta("timeline", String(e.timeline));
			s.addParameta("transaction_id", String(this.id));
			
			s.addEventListener(RestErrorEvent.RTM_FAULT, this.onFaultUndo);
			s.addEventListener(RestEvent.RTM_RESULT, this.onUndo);
			
			s.send();
		}
		
		private function onFaultUndo(e:RestErrorEvent):void{
			trace(e.code);
			trace(e.massage);
		}
		
		private function onUndo(e:RestEvent):void{
			trace("onUndo");
			var s:RestService = e.currentTarget as RestService;
			s.removeEventListener(RestErrorEvent.RTM_FAULT, this.onFaultUndo);
			s.removeEventListener(RestEvent.RTM_RESULT, this.onUndo);
			
			if(e.result_xml.@stat=="ok"){
				trace(this.process + "を取り消し");
				this.dispatchEvent(new TransactionEvent(TransactionEvent.UNDO));
			}else{
				trace("error");
			}
		}
	}
}